#pragma once
#include "../../base/Utils.h"
#include "../../net/TcpClient.h"
#include "codec.h"
namespace pubsub
{
    using namespace yhaida;
    using std::string;

    class PubSubClient : Utils::nocapyable
    {
    public:
        typedef std::function<void(PubSubClient *)> ConnectionCallback;
        typedef std::function<void(const string &topic,
                                   const string &content,
                                   Timestamp)>
            SubscribeCallback;

    public:
        PubSubClient(EventLoop *loop, const InetAddress &listenAddr);
        ~PubSubClient() = default;

        void start();
        void stop();
        bool connected() const;

        void setConnectionCallback(const ConnectionCallback &cb);

        bool subscribe(const string &topic, const SubscribeCallback &cb);
        void unsubscribe(const string &topic);
        bool publish(const string &topic, const string &content);

    private:
        void onConnection(const TcpConnectionPtr &conn);
        void onMessage(const TcpConnectionPtr &conn,
                       Buffer *buff,
                       Timestamp receiveTime);
        bool send(const string &message);

    private:
        TcpClient _client;
        TcpConnectionPtr _conn;
        ConnectionCallback _connectionCallback;
        SubscribeCallback _subscribeCallback;
    };

}